package org.yufan.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DataSourceAdvice {

    private Logger LOGGER=LoggerFactory.getLogger(DataSourceAdvice.class);

    //前置通知
    public void before(JoinPoint joinPoint){

        //获取被代理对象的方法
       MethodSignature methodSignature= (MethodSignature) joinPoint.getSignature();
       //获取被代理对象的字节码对象
        Class clazz=joinPoint.getTarget().getClass();
        LOGGER.info("被代理对象为{},调用的访问为{}",clazz.getSimpleName(),methodSignature.getName());

        //判断类上面是否有DataSource注解
        if(clazz.isAnnotationPresent(DataSource.class)){
            //获取类上面的注解
            DataSource dataSource= (DataSource) clazz.getAnnotation(DataSource.class);
            //获取注解上的标记
            LOGGER.info("当前类走{}库",dataSource.value());
            //绑定注解的标记到当前线程
            DataSourceHolder.setDataSource(dataSource.value());
        }else if(methodSignature.getMethod().isAnnotationPresent(DataSource.class)){

            DataSource dataSource= methodSignature.getMethod().getAnnotation(DataSource.class);
            //获取注解上的标记
            LOGGER.info("当前类走{}库",dataSource.value());
            //绑定注解的标记到当前线程
            DataSourceHolder.setDataSource(dataSource.value());
        }

    }



}
